package com.shxc.smarttrade.old.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapternew.TradeAccountAdapter;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.TradeAccountInfo;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myinterface.RecyclerViewItemClickListener;
import com.shxc.smarttrade.old.myview.CommonDialog;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/10/29.
 */

public class TradeAccountActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.recycler_view)
    XRecyclerView xRecyclerView;
    private LinearLayoutManager manager;
    private TradeAccountAdapter adapter;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    List<TradeAccountInfo.DataBean.UserAccountBean> uab = (List<TradeAccountInfo.DataBean.UserAccountBean>) msg.obj;
                    adapter.setDatas(uab);
                    break;
                case 1:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trade_account);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }


    private void initView() {
        tvCenter.setText("交易账户");
        manager = new LinearLayoutManager(this);
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(this);
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(this));
        xRecyclerView.setLoadingMoreEnabled(false);
        xRecyclerView.setPullRefreshEnabled(false);
        xRecyclerView.setAdapter(adapter = new TradeAccountAdapter(this));

    }

    /**
     * 获取所有经纪商账户信息
     */
    private void initData() {
        showShortDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessTokenss);
        map.put("userId", userIdss);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.TRADE_ACCOUNT_USERTYPE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                dismissShortDialog();
                showToast("网络异常");
            }
            @Override
            public void success(String response, int id) {
                if (response != null) {
                    Gson gson = new Gson();
                    TradeAccountInfo trade = gson.fromJson(response, TradeAccountInfo.class);
                    if (trade.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = trade.getData().getUserAccount();
                        handler.sendMessage(msg);

                    } else
                        showToast(trade.getErr_msg());
                }

                dismissShortDialog();
            }
        });
    }

    private void initListener() {

        adapter.setOnChangeAccountClickListener(new RecyclerViewItemClickListener() {
            @Override
            public void onItemCLick(int position, Object object) {
                final TradeAccountInfo.DataBean.UserAccountBean ub = (TradeAccountInfo.DataBean.UserAccountBean) object;

                CommonDialog commonDialog = new CommonDialog(TradeAccountActivity.this, R.style.customDialogStyle);
                commonDialog.setCanceledOnTouchOutside(true);
                commonDialog.setBaseText("提示", "是否切换账号？", "取消", "确定");
                commonDialog.setYesCLickRunAble(new Runnable() {
                    @Override
                    public void run() {
                        switchAccount(ub.getAccType());
                    }
                });
                commonDialog.show();

            }
        });
    }

    /**
     * 切换账户
     *
     * @param accType
     */
    private void switchAccount(int accType) {
        showShortDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessTokenss);
        map.put("userId", userIdss);
        map.put("accType", String.valueOf(accType));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.TRADE_ACCOUNT_CHECKTYPE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                dismissShortDialog();
                showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {
                if (response != null) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = "";
                    String errMsg = "";
                    if (!jsonObject.get("err_code").isJsonNull())
                        errCode = jsonObject.get("err_code").getAsString();
                    if (!jsonObject.get("err_msg").isJsonNull())
                        errMsg = jsonObject.get("err_msg").getAsString();
                    if (errCode.equals("0")) {
                        initData();
                        showToast("切换成功");
                        //发布通知更新数据
                        EventBus.getDefault().post(new EventDatas(EventContents.TRADE_ACCOUNT_ACTIVITY, ""));
                        finish();
                    } else
                        showToast("切换失败");
                }
                dismissShortDialog();

            }
        });

    }

    @OnClick({R.id.rl_left, R.id.btn_add_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.btn_add_account:
                startActivity(SelectBrokeOpenAccountActivity.class);
                break;
        }
    }
}
